<template>
  <div class="coponmodel">
    <el-dialog
      :showClose="false"
      title="新增优惠卷"
      :visible.sync="centerDialogVisible"
      height="50%"
      center
      width="1200px"
    >
      <el-form
        :inline="true"
        :label-position="labelPosition"
        ref="ruleForm"
        class="demo-ruleForm"
        :model="form"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="名称：" prop="name">
          <el-input style="width: 400px" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="优惠卷数量：" prop="publishTotalNumber">
          <el-input-number
            style="width: 400px"
            v-model="form.publishTotalNumber"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="优惠卷金额：" prop="methodAmount">
          <el-input-number
            style="width: 400px"
            v-model="form.methodAmount"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="可用订单金额：" prop="useConditions">
          <el-input-number
            style="width: 400px"
            v-model="form.useConditions"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="有效开始时间：" prop="startDate">
          <el-date-picker
            style="width: 400px"
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择有效开始时间（默认当天0点开始）"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效结束时间：" prop="endDate">
          <el-date-picker
            style="width: 400px"
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择有效结束时间（默认当天23:59:59结束）"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="选择商品：" prop="type">
          <div style="width: 900px; display: flex; flex-wrap: wrap">
            <el-button type="primary" @click="chooseGoodsHandle"
              >商品选择</el-button
            >
            <el-tag
              style="margin-left: 10px; margin-top: 10px"
              v-for="tag in right.transferData"
              :key="tag.id"
              closable
              :type="tag.type"
              @close="tagHandleClose(tag)"
            >
              >
              {{ tag.name }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="优惠卷描述：">
          <el-input
            style="width: 960px"
            type="textarea"
            :rows="4"
            maxlength="50"
            show-word-limit
            placeholder="请输入内容"
            v-model="form.note"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelgoodesmodel">取 消</el-button>
        <el-button type="primary" @click="savegoodesmodel">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 穿梭框 -->
    <el-dialog
      :showClose="false"
      title="商品选择"
      :visible.sync="centerDialogVisible4"
      height="50%"
      center
      width="800px"
    >
      <!-- 穿梭框开始 -->
      <div class="transfer" v-loading="loading">
        <div class="leftTransfer">
          <div class="leftTransfer_title">
            <el-checkbox
              :indeterminate="left.isIndeterminate"
              v-model="left.checkAll"
              @change="leftHandleCheckAllChange"
              >待选列表</el-checkbox
            >
            <span
              >{{ left.transferDataChecked.length }}/{{
                left.transferData.length
              }}</span
            >
          </div>
          <el-input
            style="width: 170px"
            class="transfer_input"
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="queryParams.name"
            :clearable="true"
            @clear="transferInputLeft"
          >
          </el-input>
          <el-button
            icon="el-icon-search"
            circle
            @click="transferInputLeft"
          ></el-button>
          <div style="margin: 5px 0"></div>
          <el-checkbox-group
            class="transfer_group"
            v-model="left.transferDataChecked"
            @change="leftHandleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="item in left.transferData"
              :label="item"
              :key="item.id"
              style="position: relative"
            >
              <el-tooltip
                class="item"
                effect="dark"
                :content="item.name"
                placement="right-start"
              >
                <el-button
                  type="text"
                  style="
                    color: black;
                    max-width: 200px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    text-align: left;
                  "
                  >{{ item.name }}</el-button
                >
              </el-tooltip>
            </el-checkbox>
          </el-checkbox-group>
          <el-pagination
            small
            class="pagination"
            :page-size="8"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
        <div class="transferButton">
          <el-button type="primary" @click="push">></el-button>
          <el-button type="primary" @click="del">{{ "<" }}</el-button>
        </div>
        <div class="rightTransfer">
          <div class="rightTransfer_title">
            <el-checkbox
              :indeterminate="right.isIndeterminate"
              v-model="right.checkAll"
              @change="rightHandleCheckAllChange"
              >已选列表</el-checkbox
            >
            <span
              >{{ right.transferDataChecked.length }}/{{
                right.transferData.length
              }}</span
            >
          </div>
          <!-- <el-input
            @input="transferInputRight"
            class="transfer_input"
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="right.inputValue"
          >
          </el-input> -->
          <div style="margin: 5px 0"></div>
          <div class="scrollable-container">
            <el-checkbox-group
              class="transfer_group"
              v-model="right.transferDataChecked"
              @change="rightHandleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="item in right.transferData"
                :label="item"
                :key="item.id"
                >{{ item.name }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <!-- 穿梭框结束 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelgoodesmodel4">取 消</el-button>
        <el-button type="primary" @click="savegoodesmodel4">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { AddCoupon, QueryGoodsList } from "@/api/mallApi/managementend/coupon";
export default {
  name: "BusCouponAdd",
  components: {},
  props: {
    centerDialogVisible: Boolean,
    currentRow: Object,
    enterType: Number,
    cancelSubmit: Number,
  },
  data() {
    return {
      labelPosition: "right",
      centerDialogVisible4: false,
      form: {
        limitUsing: "",
        searchBeginTime: "",
        searchEndTime: "",
        pageSize: "10",
        pageNo: "1",
        orderBy: "",
        sortBy: "",
        otherParams: {
          key: {},
        },
        requestNo: "",
        spanId: "",
        token: "",
        id: 0,
        ids: [],
        mallCode: "",
        type: null,
        name: "",
        categoryId: 0,
        method: 1,
        methodAmount: null,
        note: "",
        useConditions: 0,
        limitCategory: 0,
        limitUsing: 0,
        publishTotalNumber: 0,
        limitPagesNumberPeople: 0,
        limitDateType: 1,
        validDate: 0,
        startDate: "",
        endDate: "",
        isEnabled: 0,
        createAt: "",
        updateAt: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 2,
            max: 25,
            message: "长度在 2 到 25 个字符",
            trigger: "blur",
          },
        ],
        methodAmount: [
          {
            type: "number",
            required: true,
            message: "请输入优惠卷金额",
            trigger: "change",
          },
        ],
        startDate: [
          {
            type: "string",
            required: true,
            message: "请选择有效开始时间",
            trigger: "change",
          },
        ],
        endDate: [
          {
            type: "string",
            required: true,
            message: "请选择有效结束时间",
            trigger: "change",
          },
        ],
        // type: [
        //   { required: true, message: "请选择领取方式", trigger: "change" },
        // ],
      },
      // 穿梭框
      left: {
        inputValue: "",
        isIndeterminate: false, //半选按钮
        checkAll: false, //是否点击全选
        transferData: [], //穿梭框左侧全部数据
        transferDataAll: [], //穿梭框左侧全部数据记录
        transferDataChecked: [], //穿梭框左侧选中数据
      },
      right: {
        inputValue: "",
        isIndeterminate: false, //半选按钮
        checkAll: false, //是否点击全选
        transferData: [], //穿梭框右侧全部数据
        transferDataAll: [], //穿梭框左侧全部数据记录
        transferDataChecked: [], //穿梭框右侧选中数据
      },
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        name: "",
      },
      defaultProps: {
        label: "nickName",
        id: "userId",
      },
      loading: false,
    };
  },
  methods: {
    // 穿梭框
    savegoodesmodel4() {
      this.centerDialogVisible4 = false;
    },
    // 初始化数据
    initTransferData() {
      this.loading = true;
      QueryGoodsList(this.queryParams)
        .then((response) => {
          if (response.code !== "00000") return;
          this.loading = false;
          this.left.transferData = response.data.rows;
          this.left.transferData.map((item, index) => {
            item.current = this.queryParams.pageNum;
          });
          this.total = response.data.totalRows;
          this.left.transferDataAll = this.left.transferData;
          // 获得一个右边的数据，只有纯id
          let checkedIdArr = this.right.transferData.map((item) => {
            return item.id;
          });
          //接下里要做的是每次调用 查看左边是否有 右边的数据
          // // 左侧数据删除
          this.left.transferData = this.left.transferData.filter((item) => {
            if (!checkedIdArr.includes(item.id)) {
              return item;
            }
          });
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 左侧是否点击全选
    leftHandleCheckAllChange(val) {
      this.left.transferDataChecked = val ? this.left.transferData : [];
      this.left.isIndeterminate = false;
    },
    // 左侧勾选数据
    leftHandleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.left.checkAll = checkedCount === this.left.transferData.length;
      this.left.isIndeterminate =
        checkedCount > 0 && checkedCount < this.left.transferData.length;
    },
    // 左侧是否点击全选
    rightHandleCheckAllChange(val) {
      this.right.transferDataChecked = val ? this.right.transferData : [];
      this.right.isIndeterminate = false;
    },
    // 左侧勾选数据
    rightHandleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.right.checkAll = checkedCount === this.right.transferData.length;
      this.right.isIndeterminate =
        checkedCount > 0 && checkedCount < this.right.transferData.length;
    },
    // 穿梭框选中数据
    push() {
      // 数据移到右侧
      this.right.transferData = [
        ...this.right.transferData,
        ...this.left.transferDataChecked,
      ].sort((a, b) => {
        return a[this.defaultProps.id] - b[this.defaultProps.id];
      });
      this.right.transferDataAll = this.right.transferData;
      // 获得一个右边的数据，只有纯id
      let checkedIdArr = this.right.transferData.map((item) => {
        return item.id;
      });
      // 左侧数据删除
      this.left.transferData = this.left.transferData.filter((item) => {
        if (!checkedIdArr.includes(item.id)) {
          return item;
        }
      });
      this.left.transferDataAll = this.left.transferData;
      // 每次推送完之后，重置选中框
      this.left.transferDataChecked = [];
      this.left.isIndeterminate = false;
      this.left.checkAll = false;
    },
    // 穿梭框删除数据 回显的时候根据current回显到当前
    del() {
      //过滤当前页选中的数据
      let arr = this.right.transferDataChecked.filter((item) => {
        if (this.queryParams.pageNum == item.current) {
          return item;
        }
      });
      // 数据移到左侧
      this.left.transferData = [...this.left.transferData, ...arr].sort(
        (a, b) => {
          return a[this.defaultProps.id] - b[this.defaultProps.id];
        }
      );
      this.left.transferDataAll = this.left.transferData;
      // 获得一个右边的数据，只有纯id
      let checkedIdArr = this.right.transferDataChecked.map((item) => {
        return item.id;
      });
      // 删除选中的数据
      this.right.transferData = this.right.transferData.filter((item) => {
        if (!checkedIdArr.includes(item.id)) {
          return item;
        }
      });
      this.right.transferDataAll = this.right.transferData;
      // 每次推送完之后，重置选中框
      this.right.transferDataChecked = [];
      this.right.isIndeterminate = false;
      this.right.checkAll = false;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.initTransferData();
    },
    transferInputLeft(e) {
      this.queryParams.pageNum = 1;
      this.initTransferData();
      // if (this.left.inputValue) {
      //   this.left.transferData = this.left.transferData.filter(
      //     (p) => p[this.defaultProps.label].indexOf(this.left.inputValue) !== -1
      //   );
      // } else {
      //   this.left.transferData = this.left.transferDataAll;
      // } 
    },
    transferInputRight() {
      if (this.right.inputValue) {
        this.right.transferData = this.right.transferData.filter(
          (p) =>
            p[this.defaultProps.label].indexOf(this.right.inputValue) !== -1
        );
      } else {
        this.right.transferData = this.right.transferDataAll;
      }
    },
    tagHandleClose(tag) {
      this.right.transferData.splice(this.right.transferData.indexOf(tag), 1);
    },
    // 穿梭over
    chooseGoodsHandle() {
      this.centerDialogVisible4 = true; // 打开弹窗
    },
    cancelgoodesmodel() {
      this.$emit("cancelgoodesmodel", false);
    }, // 取消按钮 传值
    cancelgoodesmodel4(data) {
      this.centerDialogVisible4 = false;
    },
    savegoodesmodel(formName) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.methodAmount >= this.form.useConditions) {
            this.$message({
              message: "优惠卷金额不能大于可用订单金额",
              type: "warning",
            });
            return;
          }
          this.form.methodAmount = this.form.methodAmount * 100;
          this.form.useConditions = this.form.useConditions * 100;
          if (
            this.total ===
            this.right.transferData.map((item) => {
              return item.id;
            }).length
          ) {
            this.form.limitUsing = "";
          } else {
            this.form.limitUsing = this.right.transferData
              .map((item) => {
                return item.id;
              })
              .join(",");
          }
          AddCoupon(this.form)
            .then((res) => {
              if (res.code !== "00000") return;
              this.$message({
                message: "优惠卷新增成功！",
                type: "success",
              });
              this.cancelgoodesmodel();
              this.$emit("Refresh");
            })
            .catch((err) => {
              ////console.log(err);
              this.form.methodAmount = this.form.methodAmount / 100;
              this.form.useConditions = this.form.useConditions / 100;
            });
        } else {
          this.$message({
            message: "请补全优惠卷信息",
            type: "warning",
          });
          return false;
        }
      });
    },
  },
  mounted() {},
  created() {
    this.initTransferData(); //穿梭框
  },
  watch: {
    centerDialogVisible(newVal) {
      // 监听 centerDialogVisible 的变化
      if (!newVal) {
        // 当 centerDialogVisible 变为 false 时触发事件
        this.$emit("close-dialog");
      }
    },
  },
};
</script>

<style lang="scss">
//商品添加model
.coponmodel {
  width: 100vw;
  height: 100vh;
}

.transfer {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 auto;
  .transferButton {
    .el-button {
      display: block;
      margin: 10px 0;
    }
  }
  .el-checkbox {
    line-height: 30px;
  }
  .transfer_input {
    margin: 10px 15px 0 15px;
    width: 85%;
    .el-input--medium .el-input__inner {
      height: 36px;
      line-height: 36px;
      border-radius: 16px;
    }
  }
  .leftTransfer,
  .rightTransfer {
    height: 425px;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    overflow: hidden;
    background: #ffffff;
    display: inline-block;
    vertical-align: middle;
    width: 250px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    margin: 0 10px;

    .el-checkbox {
      display: block;
    }
    .pagination {
      position: absolute;
      bottom: -8px;
      right: 0;
    }
    .leftTransfer_title,
    .rightTransfer_title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      line-height: 40px;
      background: #f5f7fa;
      margin: 0;
      padding-left: 15px;
      border-bottom: 1px solid #e6ebf5;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      color: #000000;
      padding-right: 15px;
      align-items: center;
    }
  }
}
.scrollable-container {
  max-height: 380px; /* 设置最大高度，根据需要调整 */
  overflow: auto; /* 显示垂直滚动条 */
}

.transfer_group {
  padding-left: 15px;
}
</style>
